package com.ruoyi.web.controller.leaf;

import com.google.common.base.CharMatcher;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.security.Md5Utils;
import com.ruoyi.system.domain.LeafToken;
import com.ruoyi.system.service.LeafTokenService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;


/**
 * @description: TODO
 * @Author: Zhuzhi
 * @Date: 2020/12/13 下午10:10
 */
@Controller
@RequestMapping("/leaf/token")
public class LeafTokenController extends BaseController {

    private String prefix = "leaf/token";

    @Autowired
    LeafTokenService leafTokenService;

    @RequiresPermissions("leaf:token:view")
    @GetMapping()
    public String token() {
        return prefix + "/token";
    }


    @RequiresPermissions("leaf:token:list")
    @PostMapping("/list")
    @ResponseBody
    public List<LeafToken> tokenList(String namespace, String token) {
        List<LeafToken> tokenList = leafTokenService.selectLeafTokenList(namespace, token);
        return tokenList;
    }

    /**
     * 新增
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增
     */
    @RequiresPermissions("leaf:token:add")
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated LeafToken leafToken) {
        if (null != leafTokenService.selectLeafToken(leafToken.getAppId(), leafToken.getToken())) {
            return error("新增序列'" + leafToken.getAppId() + "'失败，appId名称已存在");
        }
        if (StringUtils.isBlank(leafToken.getToken())) {
            String token = buildToken();
            leafToken.setToken(token);
        }
        return toAjax(leafTokenService.insertLeafToken(leafToken));
    }

    /**
     * 删除
     */
    @RequiresPermissions("leaf:token:remove")
    @GetMapping("/remove/{id}")
    @ResponseBody
    public AjaxResult remove(@PathVariable("id") Long id) {
        return toAjax(leafTokenService.deleteLeafTokenById(id));
    }
    /**
     * Token生成
     *
     * @return
     */
    private String buildToken() {
        long time = System.currentTimeMillis();
        int random = (int) (Math.random() * Integer.MAX_VALUE);
        UUID uuid = new UUID(time, random);
        String uuidStr = CharMatcher.is('-').removeFrom(uuid.toString()).toUpperCase();
        return uuidStr;
    }
}
